import React, { Component } from 'react';
import { connect } from 'dva';
import { Modal, Form, Input, InputNumber, Table, TreeSelect, Popconfirm, Select, Button, Row, Col, } from 'antd';
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const Option = Select.Option;
var selectList = [], selectedRows = [],_dispatch;
function addSelectlist(obj) {
  var ind = selectList.indexOf(obj.id_);
  if (ind == -1) {
    selectedRows.push(obj);
    selectList.push(obj.id_);
  }
}
function delSelectlist(obj) {
  var ind = selectList.indexOf(obj.id_);
  if (ind !== -1) {
    selectList.splice(ind, 1);
    selectedRows.splice(ind, 1);
  }
}
function retSelectlist(list) {
  selectList = [];
  selectedRows = [];

  for (var i = 0; i < list.length; i++) {
    selectedRows.push(list[i]);
    selectList.push(list[i].id_);
  }
}

class SecondBorrowModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectList: [],
    };
  }
  componentWillReceiveProps(props) {
    if (!this.props.visible && props.visible) {
      retSelectlist(props.detailList);
      this.setState({ selectList });
    }
  }

  // 将选中的数据放在state里
  onSelectChange = (selectedRowKeys, selectedRows) => {
    selectList.push(selectedRowKeys);
    this.setState({ selectedRows });

  };
  onSelect = (record, selected, selectedRows) => {
    if (selected) {
      addSelectlist(record);
    } else {
      delSelectlist(record);
    }
    this.setState({ selectList });
  };
  onSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      for (var i = 0; i < changeRows.length; i++) {
        addSelectlist(changeRows[i]);
      }
    } else {
      for (var i = 0; i < changeRows.length; i++) {
        delSelectlist(changeRows[i]);
      }
    }
    this.setState({ selectList });
  };
  onSelectInvert = (selectedRows, dsd3, dsaf3) => {
    var i = 0, k = 0;
    for (i = 0; i < this.props.assetList.length; i++) {
      var obj = false;
      for (k = 0; k < selectedRows.length; k++) {
        if (this.props.assetList[i].id_ == selectedRows[k]) {
          obj = true;
        }
      }
      if (obj) {
        addSelectlist(this.props.assetList[i]);
      } else {
        delSelectlist(this.props.assetList[i]);
      }
    }
    this.setState({ selectList });
  };

  handleClearForm = () => {
    this.props.form.resetFields();
  }

  handleBrandChange= (value) => {
    this.props.form.setFieldsValue({modelId: undefined});//设置modelId控件的值为空
    _dispatch({
      type: 'borrow/queryAssetModel',
      payload: {brandId:value,typeId:this.props.form.getFieldValue("typeId")},
    })
  };

  handleTypeChange= (value) => {
    this.props.form.setFieldsValue({modelId: undefined});//设置modelId控件的值为空
    _dispatch({
      type: 'borrow/queryAssetModel',
      payload: {typeId:value,brandId:this.props.form.getFieldValue("brandId")},
    })
  };
  render() {
    _dispatch = this.props.dispatch;
    const { children, dispatch, assetType, title, detailList, roomList, assetList, assetBrandList, assetModelList,assetCurrent, assetCurrentSize, assetTotal } = this.props;
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 15 },
    };

    const paginationDetail = {
      current: assetCurrent,
      pageSize: assetCurrentSize,
      total: assetTotal,
      showSizeChanger: true,
      showTotal: (total => '共' + assetTotal + '条'),
      onShowSizeChange(current, size) {
        dispatch({
          type: 'borrow/querAssetListByParam',
          payload: { ...getFieldsValue(), ...{ 'pageNum': current, 'pageSize': size } },
        });
      },
      onChange(current) {
        dispatch({
          type: 'borrow/querAssetListByParam',
          payload: { ...getFieldsValue(), ...{ 'pageNum': current, 'pageSize': assetCurrentSize } },
        });
      },
    };
    
    const typeTreeData = (i) => {
      return i.map( d => {
        d.label = d.name;
        d.key = d.id_+'';
        d.value = d.id_+'';
        d.children = d.assetType && d.assetType.length > 0 ? typeTreeData(d.assetType) : [];
        return d;
      })
    }

    const getModel = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })
    const getBrand = data => data.map((item) => {
      return <Option key={item.id_ + ''}>{item.name}</Option>
    })

    //根据条件筛选设备
    const searchHandle = () => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          dispatch({
            type: 'borrow/querAssetListByParam',
            payload: values,
          });
        }
      });
    }
    // 点击保存将state里的选中的值放到回显给父级页面上
    const okHandler = () => {
      var arr = [];
      for (var i = 0; i < selectedRows.length; i++) {
        arr.push(selectedRows[i]);
      }
      dispatch({
        type: 'borrow/changeDetailList',
        payload: { detailList: arr, assetCurrent: 1, assetTotal: 0, assetList: [] },
      });
    };

    const rowSelection = {
      selections: true,
      selectedRowKeys: this.state.selectList,
      onSelect: this.onSelect.bind(this),
      onSelectAll: this.onSelectAll.bind(this),
      onSelectInvert: this.onSelectInvert.bind(this),
    };
    const columns = [{
      title: '资产编号',
      fixed: 'left',
      dataIndex: 'assetNo',
      key: 'assetNo',
      width: 150
    }, {
      title: '资产分类',
      dataIndex: 'typeName',
      key: 'typeName',
      width: 120
    }, {
      title: '设备名称',
      dataIndex: 'assetName',
      key: 'assetName',
      width: 150
    }, {
      title: '品牌',
      dataIndex: 'brandName',
      key: 'brandName',
      width: 100,
    }, {
      title: '设备型号',
      dataIndex: 'modelName',
      key: 'modelName',
      width: 120,
    }, {
      title: '设备序列号',
      dataIndex: 'serialNo',
      key: 'serialNo',
      width: 150,
    }, {
      title: 'RFID编码',
      dataIndex: 'rfidNo',
      key: 'rfidNo',
      width: 100,
    }, {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 70,
      render: (value, row, index) => {
        return (
          value == 1 ? "在库" : value == 2 ? "已上架" : value == 3 ? "已报废" : ''
        )
      }
    }, {
      title: '所在机房',
      dataIndex: 'roomName',
      key: 'roomName',
      width: 160,
    }, {
      title: '所在机柜',
      dataIndex: 'rackName',
      key: 'rackName',
      width: 120,
    }, {
      title: '起始U位',
      dataIndex: 'startU',
      key: 'startU',
      width: 80,
    }, {
      title: '购置时间',
      dataIndex: 'buyTime',
      key: 'buyTime',
      width: 120,
    }, {
      title: '维保结束日期',
      dataIndex: 'expirationTime',
      key: 'expirationTime',
      width: 120,
    }];

    return (
      <span>

        <Modal
          maskClosable={this.props.maskClosable}
          confirmLoading={this.props.confirmLoading}
          title={this.props.title}
          width={1000}
          visible={this.props.visible}
          onOk={okHandler.bind(this)}
          onCancel={this.props.onCancel}
          key={this.props.newKey}

        >
          <div style={{ backgroundColor: '#fff' }}>
            <div style={{}}>
              <div style={{ width: '100%', backgroundColor: '#fff', paddingLeft: '20px' }}>
                <Form layout="inline" style={{ marginTop: '-16px' }}>
                  <FormItem style={{ marginBottom: '0px' }}>
                    {getFieldDecorator('searchStatusType', { initialValue: 5 })(
                      <Input type="hidden" />
                    )}
                  </FormItem>
                  <Row>
                  <Col span={6}>
                    <FormItem
                    {...formItemLayout}
                      label="资产分类"
                      hasFeedback
                    >
                      {
                        getFieldDecorator('typeId')(
                          <TreeSelect
                            showSearch
                            style={{ width: '170px' }} 
                            treeNodeFilterProp="title"
                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                            placeholder="请选择资产分类"
                            allowClear
                            treeDefaultExpandAll
                            onChange={this.handleTypeChange}
                            treeData={typeTreeData(assetType)}
                          >
                          </TreeSelect>
                        )
                      }
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem
                      label="品牌"
                      {...formItemLayout}
                      hasFeedback
                    >
                      {getFieldDecorator('brandId')(
                        <Select
                          style={{ width: '160px' }} 
                          showSearch
                          allowClear
                          onChange={this.handleBrandChange}
                          placeholder="请选择设备品牌">

                          {getBrand(assetBrandList)}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem
                      label="设备型号"
                      {...formItemLayout}
                      hasFeedback
                    >
                      {getFieldDecorator('modelId')(
                        <Select
                          style={{ width: '170px' }} 
                          showSearch
                          allowClear
                          placeholder="请选择设备型号">

                          {getModel(assetModelList)}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={6}>
                    <FormItem                        
                      label="设备名称"
                      {...formItemLayout}
                      hasFeedback
                    >
                      {
                        getFieldDecorator('assetName')(<Input style={{ width: '164px' }}  placeholder="请输入设备名称查找" />)
                      }
                    </FormItem>
                  </Col>                                   
                </Row>
                <Row style={{marginTop:'20px'}}>
                  <Col span={6}>
                    <FormItem                        
                      label="设备编号"
                      {...formItemLayout}
                      hasFeedback
                    >
                      {
                        getFieldDecorator('assetNo')(<Input style={{ width: '170px' }}  placeholder="请输入设备编号查找" />)
                      }
                    </FormItem>
                  </Col>   
                  <Col span={6}>
                    <FormItem                          
                          label="RFID号"
                          {...formItemLayout}
                          hasFeedback
                        >
                        {
                          getFieldDecorator('rfidNo')(<Input style={{ width: '160px' }}  placeholder="请输入RFID号查找" />)
                        }
                      </FormItem> 
                  </Col> 
                  <Col span={6}>
                        <FormItem
                          label="序列号"
                          {...formItemLayout}
                          hasFeedback
                        >
                        {
                          getFieldDecorator('serialNo')(<Input style={{ width: '170px' }}   placeholder="请输入序列号查找"/>)
                        }
                      </FormItem>                     
                  </Col>                
                  <Col span={6}>
                      <div style={{textAlign: 'right' ,paddingRight:'20px'}}>
                          <Button size="large" style={{ marginRight: '10px' }} onClick={searchHandle} type="primary" className='ant-search-btn'>搜索</Button>
                          <Button size="large" htmlType="reset" onClick={this.handleClearForm}>清空</Button>
                      </div>
                  </Col>
                </Row>    

                </Form>
              </div>
              <div style={{}}>
                <div style={{ width: '100%', padding: "10px 20px 20px 20px" }}>
                  <Table columns={columns}
                    rowSelection={rowSelection}
                    rowKey={record => record.id_}
                    dataSource={assetList}
                    pagination={paginationDetail}
                    scroll={{ x: 1800 }}
                  />
                </div>
              </div>
            </div>
          </div>
        </Modal>
      </span>
    );
  }
}

export default Form.create()(SecondBorrowModal);
